package com.itheima.tliasmanagementspringboot.aspect;

import com.itheima.tliasmanagementspringboot.common.R;
import com.itheima.tliasmanagementspringboot.pojo.Emp;
import com.itheima.tliasmanagementspringboot.pojo.EmpLoginLog;
import com.itheima.tliasmanagementspringboot.service.EmpLoginLogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Component
@Slf4j
@Aspect
public class LoginAspect {
    /*@Autowired
    HttpServletRequest httpServletRequest;*/
    @Autowired
    EmpLoginLogService empLoginLogService;

    //疑问,需要加入IOC然后在这注入吗
    EmpLoginLog empLoginLog = new EmpLoginLog();

    @Around("execution(* com.itheima.tliasmanagementspringboot.controller.LoginController.login(..))")
    public Object loginAround(ProceedingJoinPoint pjp)  {
        //1.前置
        System.out.println("登录前置");
        long start = System.currentTimeMillis();
        /*EmpLoginLog empLoginLog = new EmpLoginLog();*/
        //登录时间
        empLoginLog.setLoginTime(LocalDateTime.now());//登录时间
        //用户名
        Emp emp = (Emp) pjp.getArgs()[0];
        empLoginLog.setUsername(emp.getUsername());

        //密码
        empLoginLog.setPassword(emp.getPassword());

        //改进部分
        empLoginLog.setJwt(null);
        empLoginLog.setIsSuccess(Short.parseShort("0"));
        //执行原始方法,并接收返回值
        Object result = null;
        try {
            result = pjp.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        empLoginLog.setCostTime(System.currentTimeMillis() - start);
        if (result == null) {
            return result;
        }

        //执行后
        //登录是否成功
        //判断data数据是否为空即可
        R empResult = (R) result;
        Short isSuccess = 1;
        if (empResult.getData() == null){
            isSuccess = 0;
        }
        empLoginLog.setIsSuccess(isSuccess);
        //jwt令牌
        empLoginLog.setJwt((String)empResult.getData());
        long end = System.currentTimeMillis();
        //操作耗时
        empLoginLog.setCostTime(end - start);
        //empLoginLogService.insert(empLoginLog);
        return result;
    }
    @After("execution(* com.itheima.tliasmanagementspringboot.controller.LoginController.login(..))")
    public void loginAfter(JoinPoint jp){
        System.out.println("后置通知");
        empLoginLogService.insert(empLoginLog);
    }

}
